import 'dart:convert';
import 'dart:math' as math;

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:situation/app/theme/app_theme.dart';
import 'package:situation/app/theme/gaps.dart';
import 'package:situation/data/store/auth_store.dart';
import 'package:situation/data/store/config_store.dart';
import 'package:situation/domain/chat/MessageDomain.dart';
import 'package:situation/domain/chat/msg.dart';
import 'package:situation/domain/db/im_msg_content_domain.dart';
import 'package:situation/resources/assets.dart';
import 'package:situation/shared/util/util_mk.dart';
import 'package:situation/widgets/PlayVideo.dart';
import 'package:situation/widgets/mk_load_image.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'package:wukongimfluttersdk/model/wk_image_content.dart';
import 'package:wukongimfluttersdk/model/wk_media_message_content.dart';
import 'package:wukongimfluttersdk/model/wk_video_content.dart';
import 'package:wukongimfluttersdk/type/const.dart';

import 'controller.dart';
import 'state.dart';

class CommunicationChatPage extends StatefulWidget {
  const CommunicationChatPage({Key? key}) : super(key: key);

  @override
  State<CommunicationChatPage> createState() => _CommunicationChatPageState();
}

class _CommunicationChatPageState extends State<CommunicationChatPage> {
  final CommunicationChatController controller = Get.put(
    CommunicationChatController(),
  );
  final CommunicationChatState state =
      Get.find<CommunicationChatController>().state;


  bool _shrinkWrap = false;

  @override
  void initState() {
    super.initState();

  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget _buildMessageItem(int index) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final message = state.messages[index];
        final maxWidth = math.min(constraints.maxWidth - 124, 400.0);
        Widget? imgWidget;
        Widget? msgWidget;
        if (message != null) {
          msgWidget = Container(
            padding: const EdgeInsets.all(8),
            decoration: BoxDecoration(
              color: Colors.grey.withOpacity(0.1),
              borderRadius: BorderRadius.only(
                topLeft: const Radius.circular(24),
                topRight: const Radius.circular(24),
                bottomLeft: const Radius.circular(24),
                bottomRight: const Radius.circular(24),
              ),
            ),
            constraints: BoxConstraints(maxWidth: maxWidth),
            child: _buildMsgContent(message),
          );
        }
        Widget contentWidget = Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            if (imgWidget != null) imgWidget,
            if (imgWidget != null && msgWidget != null)
              const SizedBox(height: 8),
            if (msgWidget != null) msgWidget,
          ],
        );

        var picWidget = Padding(
          padding: const EdgeInsets.only(right: 8),
          child: ClipOval(
            child:
                controller.remoteHeadImgUrl == null
                    ? TDAvatar(text: controller.name,
                    type: TDAvatarType.customText,
                    size: TDAvatarSize.small)
                    : TDAvatar(
                      avatarUrl:
                          ConfigStore.to.baseFileUrl +
                          "/" +
                          controller.remoteHeadImgUrl,
                  type: TDAvatarType.normal,
                      size: TDAvatarSize.small,
                    ),
          ),
        );

        var myImgWidget = Padding(
          padding: const EdgeInsets.only(right: 8),
          child: TDAvatar(
            avatarUrl: AuthStore.to.getUserAvatar(),
            size: TDAvatarSize.small,
          ),
        );

        return Container(
          margin: EdgeInsets.only(top: 8, bottom: 8, left: 16, right: 16),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: [
              message.wkMsg.fromUID == AuthStore.to.profile.idcard
                  ? const Spacer()
                  : const SizedBox(),
              message.wkMsg.fromUID != AuthStore.to.profile.idcard
                  ? picWidget
                  : const SizedBox(),
              Gaps.hGap4,
              contentWidget,
              Gaps.hGap4,
              message.wkMsg.fromUID == AuthStore.to.profile.idcard
                  ? myImgWidget
                  : const SizedBox(),
              message.wkMsg.fromUID != AuthStore.to.profile.idcard
                  ? const Spacer()
                  : const SizedBox(),
            ],
          ),
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).unfocus();
      },
      child: Scaffold(
        appBar: TDNavBar(title: "${controller.name}"),
        resizeToAvoidBottomInset: true,
        body: Column(
          children: [
            Expanded(
              child: EasyRefresh(
                onRefresh: () {
                  controller.getPrevious();
                },
                onLoad: () {
                  controller.onLoad();
                },
                child: Obx(
                  () => CustomScrollView(
                    controller: controller.scrollController,
                    shrinkWrap: _shrinkWrap,
                    clipBehavior: Clip.none,
                    slivers: [
                      SliverList(
                        delegate: SliverChildBuilderDelegate((context, index) {
                          return _buildMessageItem(index);
                        }, childCount: state.messages.length),
                      ),
                    ],
                  ),
                ),
              ),
            ),

            Container(
              color: Colors.grey.shade100,
              child: SafeArea(
                child: Column(
                  children: [
                    Center(
                      child: Container(
                        color: Colors.grey.shade100,
                        child: Padding(
                          padding: const EdgeInsets.only(
                            top: 8,
                            left: 2,
                            right: 8,
                            bottom: 8,
                          ),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Expanded(
                                child: Padding(
                                  padding: const EdgeInsets.symmetric(
                                    horizontal: 8,
                                    vertical: 0,
                                  ),
                                  child: TDInput(
                                    backgroundColor: Colors.white,
                                    size: TDInputSize.small,
                                    controller:
                                        controller.textEditingController,
                                    maxLines: 1,
                                  ),
                                ),
                              ),
                              // IconButton(
                              //   onPressed: () {},
                              //   icon: const Icon(Icons.tag_faces, size: 30,),
                              // ),
                              Obx(
                                () => AnimatedSwitcher(
                                  duration: const Duration(milliseconds: 500),
                                  child:
                                      state.inTyping
                                          ? TDButton(
                                            text: '发送',
                                            size: TDButtonSize.small,
                                            theme: TDButtonTheme.light,
                                            onTap: controller.handleSend,
                                          )
                                          : IconButton(
                                            onPressed: controller.changeVisible,
                                            icon: const Icon(
                                              Icons.add_circle_outline,
                                              size: 30,
                                            ),
                                          ),
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    Obx(
                      () => Visibility(
                        visible: state.visible,
                        child: _buildBottom(),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildBottom() {
    return Container(
      width: Get.width,
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(AppTheme.iDefaultRadius),
      ),
      child: Wrap(
        alignment: WrapAlignment.start,
        children: [
          _buildIntellCategoryItem(Assets.chatPic, "图片", () {
            controller.uploadPic();
          }),
          _buildIntellCategoryItem(Assets.chatVideo, "视频", () {
            controller.uploadVideo();
          }),
          // _buildIntellCategoryItem(Assets.chatPosition, "位置", () {
          //   controller.getLocation();
          // }),
          _buildIntellCategoryItem(Assets.chatYuyin, "语音呼叫", () {
            controller.voiceCall();
          }),
          _buildIntellCategoryItem(Assets.chatShipin, "视频呼叫", () {
            controller.videoCall();
          }),
          // _buildIntellCategoryItem(Assets.chatJianshi, "视频查看", () {}),
        ],
      ),
    );
  }

  _buildIntellCategoryItem(icon, name, onTap) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        width: (Get.width - AppTheme.iDefaultPadding * 2) / 4,
        padding: EdgeInsets.all(AppTheme.iDefaultPadding),
        child: Column(
          children: [
            MkLoadImage(icon, width: 36, height: 36),
            Gaps.vGap8,
            Text(name),
          ],
        ),
      ),
    );
  }

  _buildMsgContent(UIMsg message) {
    if (message.wkMsg.contentType == WkMessageContentType.text) {
      return Text(message.getShowContent());
    }

    if (message.wkMsg.contentType == WkMessageContentType.image) {

      WKImageContent wkImageContent = message.wkMsg.messageContent as WKImageContent;
      return GestureDetector(
        onTap: () {
          TDImageViewer.showImageViewer(
            context: context,
            images: [ConfigStore.to.baseFileUrl + wkImageContent.url],
          );
        },
        child: MkLoadImage(ConfigStore.to.baseFileUrl + wkImageContent.url, width: 120),
      );
    }

    if (message.wkMsg.contentType == WkMessageContentType.video) {
      WKVideoContent wkVideoContent = message.wkMsg.messageContent as WKVideoContent;
      return GestureDetector(
        onTap: () {
          UtilMk.openBottomSheet(
            480,
            "视频",
            Container(
              height: 400,
              clipBehavior: Clip.hardEdge,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(
                  AppTheme.iDefaultRadius * 2,
                ),
              ),
              child: PlayVideo(url: ConfigStore.to.baseFileUrl + wkVideoContent.url),
            ),
          );
        },
        child: Stack(
          children: [
            Container(
              clipBehavior: Clip.hardEdge,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(
                  AppTheme.iDefaultRadius * 2,
                ),
              ),
              child: MkLoadImage(ConfigStore.to.baseFileUrl + wkVideoContent.cover, width: 120),
            ),
            Positioned(
              child: Icon(Icons.play_circle, size: 50, color: Colors.white),
              left: 0,
              right: 0,
              bottom: 0,
              top: 0,
            ),
          ],
        ),
      );
    }
  }
}
